package com.ecar.api.pay.wx;
/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.net.URL;
import java.security.KeyStore;

/**
 * 申请退款需要证书，用此类发起请求
 */
class SSLClient {

	private static SSLConnectionSocketFactory SSLSocketFacktory(KeyStore keyStore, final char[] chars) throws Exception {
		return new SSLConnectionSocketFactory(
			SSLContexts.custom().loadKeyMaterial(keyStore, chars).build(),
			new String[]{"TLSv1"},
			null,
			SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
	}

	private static String requestSSL(String url, String data, SSLConnectionSocketFactory sslsf) throws Exception {
		try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build()) {
			HttpPost httpost = new HttpPost(url);
			httpost.addHeader("Connection", "keep-alive");
			httpost.addHeader("Accept", "*/*");
			httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			httpost.addHeader("Host", "api.mch.weixin.qq.com");
			httpost.addHeader("X-Requested-With", "XMLHttpRequest");
			httpost.addHeader("Cache-Control", "max-age=0");
			httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
			httpost.setEntity(new StringEntity(data, "UTF-8"));
			try (CloseableHttpResponse response = httpclient.execute(httpost)) {
				HttpEntity entity = response.getEntity();

				String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
				EntityUtils.consume(entity);
				return jsonStr;
			}
		}
	}

	static String doRefund(String url, String data) throws Exception {
		URL resUrl = SSLClient.class.getClassLoader().getResource("apiclient_cert.p12");
		final char[] chars = WeixinPayConfig.mch_id.toCharArray();
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		if (resUrl != null) {
			URI uri = resUrl.toURI();
			try (FileInputStream instream = new FileInputStream(new File(uri))) {
				keyStore.load(instream, chars);
			}
		}

		return requestSSL(url, data, SSLSocketFacktory(keyStore, chars));
	}

	static String doRefundH5(String url, String data) throws Exception {
		URL resUrl = SSLClient.class.getClassLoader().getResource("apiclient_cert_fws.p12");
		final char[] chars = WeixinPayConfig.FWS_mchid.toCharArray();
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		if (resUrl != null) {
			URI uri = resUrl.toURI();
			try (FileInputStream instream = new FileInputStream(new File(uri))) {
				keyStore.load(instream, chars);
			}
		}

		return requestSSL(url, data, SSLSocketFacktory(keyStore, chars));
	}
}
